#include <iostream>
#include <unordered_map>
#include "Protocol.hpp"
#include "../Connection.hpp"
#include "Request&&Response.hpp"
#include "../RoomPlayers.hpp"

extern std::unordered_map<std::string, Room *> rooms;
extern std::unordered_map<int, std::string> fd_to_room_number;

class RequestDestoryRoom : public Request
{
public:
	RequestDestoryRoom() {}

	virtual bool Serialize(std::string *msg)
	{
		return true;
	}
	virtual bool Deserialize(const Json::Value &root)
	{
		return true;
	}

	~RequestDestoryRoom() {}

private:
};

class ResponseDestoryRoom : public Response
{
public:
	ResponseDestoryRoom() {}

	virtual bool Serialize(std::string *msg)
	{
		// Json::Value root;
		// root["return"] = _return;
		// Json::FastWriter writer;
		// *msg = writer.write(root);
		// // std::cout << *msg << std::endl;
		// _return  = 0;
		return true;
	}

	// 收到客户端发来的销毁房间的请求时，服务器端需要向处在房间的其他人发送退出房间信号
	virtual bool ServerHandler(const RequestDestoryRoom *req, Connection *conn)
	{
		std::vector<Player> &players = rooms[fd_to_room_number[conn->GetFd()]]->GetPlayers();
		std::string msg;
		Json::Value root;
		root["server_type"] = DestoryRoom;
		Json::FastWriter writer;
		msg = writer.write(root);
		Package(msg, &msg);
		for (int i = 0; i < players.size(); i++)
		{
			if (players[i].Exist())
			{
				Connection *conn_player = players[i].GetConnection();
				// std::cout << "conn_player->GetOutbuffer() " << conn_player->GetOutbuffer() << std::endl;
				if (conn != conn_player)
				{
					conn_player->GetOutbuffer() += msg;
					// std::cout << "conn_player->GetOutbuffer() " << conn_player->GetOutbuffer() << std::endl;
					conn_player->GetWriter()(conn_player);
				}
			}
		}

		// 本地 删除
		std::string room_number;
		for (int i = 0; i < players.size(); i++)
		{
			if (players[i].Exist())
			{
				Connection *conn_player = players[i].GetConnection();
				room_number = fd_to_room_number[conn_player->GetFd()];
				fd_to_room_number.erase(conn_player->GetFd());
			}
		}
		delete rooms[room_number];
		rooms.erase(room_number);

		return true;
	}

	virtual bool Deserialize(const std::string &result)
	{
		return true;
	}

	virtual ~ResponseDestoryRoom() {}

private:
	int _return = 0;
};
